import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getList } from '@/api/system/authority.js'
import { projectUserInfo } from '@/api/project/project'
import myStroage from '@/utils/sessionStorage'
const user = {
  state: {
	userIsOffine:true,
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],            // 角色信息
    privileges: [],               // 菜单权限
    buttonPrivileges: [],         // 按钮权限
    projectPrivileges: [],
    projectButtonPrivileges: [],
    setting: {
      articlePlatform: []
    },
    userName: "",
	appAuthList: []
  },

  mutations: {
	  SET_USERISOFFINE: (state, userIsOffine) => {
		state.userIsOffine = userIsOffine
	  },
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PRIVILEGES: (state, privileges) => {
      state.privileges = privileges
    },
    SET_BUTTON_PRIVILEGES: (state, buttonPrivileges) => {
      state.buttonPrivileges = buttonPrivileges
    },
    SET_PROJECT_PRIVILEGES: (state, projectPrivileges) => {
      state.projectPrivileges = projectPrivileges
    },
    SET_PROJECT_BUTTON_PRIVILEGES: (state, projectButtonPrivileges) => {
      state.projectButtonPrivileges = projectButtonPrivileges
    },
    setUserName:(state,userName)=>{
      state.userName = userName
    },
	setAppAuthList: (state, value) => {
		state.appAuthList = value
	}
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo).then(response => {
          if (response.success) {
            commit('SET_TOKEN', response.result)
            setToken(response.result)
            resolve(response)
          } else {
            reject()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
	
	/** 获取app所有权限 */
	getAppAuthList({ commit }) {
		return new Promise(resolve => {
			getList({ scope: 'system' }).then(res => {
				if (res && Array.isArray(res.result)) {
					commit('setAppAuthList', res.result.filter(item => item.code.indexOf('app') === 0))
				}
			}).finally(() => {
				resolve()
			})
		})
	},

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          const data = response
          const roleArr = data.result.roles
          const privilegesArr = []
          const privilegesButtonArr = []
		  
          data.result.privileges.forEach(function(item) {
            if (item.type === 'menu') {
              privilegesArr.push(item.code)
            } else {
              privilegesButtonArr.push(item.code)
            }
          })
		  
          if (privilegesArr.length === 0) {
            privilegesArr.push('p_zhuye')
          }
		  // 检查是否缺失父权限
		  const getParent = id => {
			const temp = state.appAuthList.find(item => item.id === id)
			if (temp) {
				return temp
			}
			return null
		  }
		  for (const item of privilegesButtonArr) {
			  if (item.indexOf("app") === 0) {
				  const temp = state.appAuthList.find(item1 => item1.code === item)
				  if (temp && temp.treeLevel === 3 && temp.parentId) {
				  	const data = getParent(temp.parentId)
				  	if (data && !privilegesArr.includes(data.code)) {
				  		privilegesArr.push(data.code)
				  	}
				  }
			  }
		  }
		  console.log(privilegesArr);
          // const buttonPrivilegesArr = data.result.privileges
          commit('SET_ROLES', roleArr)
          commit('SET_PRIVILEGES', privilegesArr)
          commit('SET_BUTTON_PRIVILEGES', privilegesButtonArr)
          commit('SET_NAME', data.result.user ? data.result.user.name : data.result.user.name)
          commit('SET_AVATAR', data.result.user ? data.result.user.photo : '')
		  data.result.user.org=data.result.org
          commit('setUserName',data.result.user)
          // commit('SET_INTRODUCTION', data.introduction)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    },
    setPrivilege({ commit }, type) {
      if (type === 'system') {
        commit('SET_PROJECT_PRIVILEGES', [])
        commit('SET_PROJECT_BUTTON_PRIVILEGES', [])
      } else {
        commit('SET_PRIVILEGES', [])
        commit('SET_BUTTON_PRIVILEGES', [])
      }
    },
    // 获取项目权限
    getProjectPrivileges({ commit }) {
      return new Promise((resolve, reject) => {
        var p1 = new Promise((resolve) => {
          getUserInfo().then(response => {
            resolve(response)
          })
        })
        var p2 = new Promise((resolve) => {
          projectUserInfo({ projectId: JSON.parse(myStroage.getStorage('project')).id }).then(response => {
            resolve(response)
          })
        })
        Promise.all([p1, p2]).then(res => {
          // res[0]    人员信息
          // res[1]    项目用户信息
          if (res[0].success) {
            const data = res[0]
            const roleArr = data.result.roles
            commit('SET_ROLES', roleArr)
            commit('SET_NAME', data.result.user ? data.result.user.name : data.result.user.name)
            commit('SET_AVATAR', data.result.user ? data.result.user.photo : '')
            commit('setUserName',data.result.user)
          }
          if (res[1].success) {
            const privilegesArr = []
            const privilegesButtonArr = []
            if (res[1].result.projectPrivileges && res[1].result.projectPrivileges.length > 0) {
              res[1].result.projectPrivileges.forEach(function(item) {
                if (item.type === 'menu') {
                  privilegesArr.push(item.code)
                } else {
                  privilegesButtonArr.push(item.code)
                }
              })
            }
            if (privilegesArr.length === 0) {
              privilegesArr.push('p_zhuye')
            }
            commit('SET_PROJECT_PRIVILEGES', privilegesArr)
            commit('SET_PROJECT_BUTTON_PRIVILEGES', privilegesButtonArr)
          }
          resolve(res[1])
        })
      })
    }
  }
}

export default user
